package jch.learn.java.advanced.chapter2_InputAndOutput;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;

public class TestFilesRW {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get(TestFilesRW.class.getResource("/chapter2/demo.txt").getPath().substring(1));
        System.out.println("path: " + path);
        byte[] bytes = Files.readAllBytes(path);
        System.out.println(Arrays.toString(bytes));

        String content = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("content: " + content);

        System.out.println("写出文件：张三");
        Files.write(path,"张三".getBytes(StandardCharsets.UTF_8));

        System.out.println("追加写出文件内容：李四");
        Files.write(path,"李四".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);

        System.out.println("将文件按行序列读入：");
        List<String> line = Files.readAllLines(path);
        line.forEach(System.out::println);

        // 按行写入
//        Files.write(path,line);
        Files.write(path,line,StandardOpenOption.APPEND);

        InputStream in = Files.newInputStream(path);
//        DataInputStream inData = new DataInputStream(in);
        System.out.println("inData:" + in.read());
        in.close();

        OutputStream out = Files.newOutputStream(path,StandardOpenOption.APPEND);
        DataOutputStream outData = new DataOutputStream(out);
        outData.writeInt(1234);
        outData.close();

        Reader reader = Files.newBufferedReader(path,StandardCharsets.UTF_8);
        int i = reader.read();
        System.out.println(i);
        reader.close();

        Writer writer = Files.newBufferedWriter(path,StandardCharsets.UTF_8,StandardOpenOption.APPEND);
        writer.write("王五");
        writer.close();
    }

}
